package com.koron.common.web.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.koron.common.web.bean.PicAccessoryBean;
import com.koron.common.web.bean.UserSatisfiedBean;
import com.koron.common.web.bean.UserSatisfiedQueryBean;
import com.koron.common.web.mapper.InteractiveMapper;
import com.koron.css2.baseConfig.bean.BaseAccessoryMetadataBean;
import com.koron.css2.baseConfig.bean.BaseReceiptAccessoryBean;
import com.koron.css2.baseConfig.mapper.BaseAccessoryMetadataMapper;
import com.koron.css2.baseConfig.mapper.BaseReceiptAccessoryMapper;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.util.Constant;
import com.koron.util.DBSourceUtils;
import com.koron.util.Tools;
import com.koron.util.Upload;
import com.koron.util.encode.BASE64DecodedMultipartFile;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.koron.ebs.mybatis.SessionFactory;
import org.koron.ebs.mybatis.TaskAnnotation;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import java.util.List;
import java.util.Map;

/**
 * 交互机业务层
 *
 * @author: zhongxj
 * @date: 2020-07-23 15:54
 **/

public class InteractiveService {

    public static Logger logger = LogManager.getLogger(InteractiveService.class);

    /**
    * @description:  保存用户满意度
    * @author: zhongxj
    * @date: 2020/7/23 16:13
    */
    @TaskAnnotation("satisfiedAdd")
    public MessageBean<?> satisfiedAdd(SessionFactory factory, UserSatisfiedBean userSatisfiedBean){
        InteractiveMapper mapper = factory.getMapper(InteractiveMapper.class, DBSourceUtils.getDbEnv(userSatisfiedBean.getCompanyNo()));
        userSatisfiedBean.setId(Tools.getObjectId());
        mapper.satisfiedAdd(userSatisfiedBean);
        MessageBean<String> msg = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "保存成功", String.class);
        return msg;
    }

    /**
    * @description:  保存用户满意度
    * @author: zhongxj
    * @date: 2020/7/23 16:13
    */
    @TaskAnnotation("satisfiedList")
    public MessageBean<?> satisfiedList(SessionFactory factory, UserSatisfiedQueryBean bean) {
        // 分页
        try {
            PageHelper.startPage(bean.getPage(), bean.getPageCount());
            InteractiveMapper mapper = factory.getMapper(InteractiveMapper.class, DBSourceUtils.getDbEnv(bean.getCompanyNo()));
            List<UserSatisfiedBean> list = mapper.satisfiedList(bean);
            //输出分页结果
            MessageBean<PageInfo> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "查询成功", PageInfo.class);
            info.setData(new PageInfo<>(list));
            return info;
        } catch (Exception e) {
            logger.error("客户满意度查询失败" + e.getMessage(), e);
            return MessageBean.create(Constant.MESSAGE_INT_FAIL, "查询失败", null);
        }
    }

    /**
    * @description: 签字图片上传
    * @author: zhongxj
    * @date: 2020/7/24 17:05
    */
    @TaskAnnotation("signPicUpload")
    public MessageBean<?> signPicUpload(SessionFactory factory, UserInfoBean userInfo,RequestBean req){
        // 交互机传过来仅有base64没有格式
        try {
            Map<String, String> map = JsonUtils.objectToPojo(req.getData(), Map.class);
            // 用于存单据id
            String code = req.getBusicode();
            for (Map.Entry<String, String> entry : map.entrySet()) {
                // 指纹没有的直接跳过
                if (StringUtils.isBlank(entry.getValue())) {
                    continue;
                }
                String key = entry.getKey();
                String value = entry.getValue();
                StringBuilder sb = new StringBuilder();
                if(key.equals("SignPdfBase64")){
                    //  签字pdf
                    sb.append("data:application/pdf;base64,");
                }else if(key.equals("SignNameBase64")){
                    // 签名图片
                    sb.append("data:image/png;base64,");
                }else if(key.equals("FingerPrintBase64")){
                    // 指纹图片
                    sb.append("data:image/png;base64,");
                }
                sb.append(value);
                MultipartFile file = BASE64DecodedMultipartFile.base64ToMultipart(sb.toString());
                String path = Upload.upload(file);
                if (StringUtils.isNotBlank(path)) {
                    addAccessoryData(factory,file,userInfo,path,code,"signature");
                }
            }
            MessageBean<String> msg = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "上传成功", String.class);
            return msg;
        } catch (Exception e) {
            logger.error("上传签字图片失败" + e.getMessage(), e);
            return MessageBean.create(Constant.MESSAGE_INT_FAIL, "上传失败", null);
        }
    }


    /**
    * @description: 高拍仪图片上传
    * @author: zhongxj
    * @date: 2020/7/24 17:05
    */
    @TaskAnnotation("picUpload")
    public MessageBean<?> picUpload(SessionFactory factory, UserInfoBean userInfo, PicAccessoryBean picAccessoryBean){
        // 交互机传过来仅有base64没有格式
        try {
            String data = picAccessoryBean.getData();
            String receiptId = picAccessoryBean.getReceiptId();
            String accessoryNo = picAccessoryBean.getAccessoryNo();
            StringBuilder sb = new StringBuilder();
            sb.append("data:image/bmp;base64,");
            sb.append(data);
            MultipartFile file = BASE64DecodedMultipartFile.base64ToMultipart(sb.toString());
            String path = Upload.upload(file);
            if (StringUtils.isNotBlank(path)) {
                addAccessoryData(factory,file,userInfo,path,receiptId,accessoryNo);
            }
            MessageBean<String> msg = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "上传成功", String.class);
            return msg;
        } catch (Exception e) {
            logger.error("上传签字图片失败" + e.getMessage(), e);
            return MessageBean.create(Constant.MESSAGE_INT_FAIL, "上传失败", null);
        }
    }

    /**
     *@description:数据库插入附件信息
     * @param factory
     * @param file
     * @param userInfo 用户信息
     * @param path 服务器路径
     * @param code 单据id
     * @param accessoryNo 附件类型
     */
    private void addAccessoryData(SessionFactory factory,MultipartFile file,UserInfoBean userInfo,String path,String code,String accessoryNo){
        BaseAccessoryMetadataMapper metadataMapper = factory.getMapper(BaseAccessoryMetadataMapper.class);
        BaseReceiptAccessoryMapper mapper = factory.getMapper(BaseReceiptAccessoryMapper.class);
        BaseAccessoryMetadataBean metadata = new BaseAccessoryMetadataBean();
        String metadataId = Tools.getObjectId();
        metadata.setAccessoryPath(path);
        metadata.setAccessoryName(FilenameUtils.getName(file.getOriginalFilename()));
        metadata.setId(metadataId);
        metadata.setAccessorySize(file.getSize());
        metadata.setAccessoryType(file.getContentType());
        metadata.setCreateAccount(userInfo.getUserInfo().getAcount());
        metadata.setCreateName(userInfo.getUserInfo().getName());
        metadata.setSourceFlag("1");
        metadataMapper.insert(metadata);
        BaseReceiptAccessoryBean bean = new BaseReceiptAccessoryBean();
        bean.setId(Tools.getObjectId());
        bean.setMetadataId(metadataId);
        bean.setCreateAccount(userInfo.getUserInfo().getAcount());
        bean.setCreateName(userInfo.getUserInfo().getName());
        bean.setAccessoryName(FilenameUtils.getName(file.getOriginalFilename()));
        mapper.insert(bean);
    }


}
